//
//  BTMyCollectionsVC.m
//  BaxTer
//
//  Created by 陈武琦 on 16/9/1.
//  Copyright © 2016年 陈武琦. All rights reserved.
//

#import "BTCouseListVC.h"
#import "CWQ_courseIntroductionCell.h"
#import "BTCollectionBottomMenuView.h"
#import "CWQ_tableView.h"
#import "BTCourseDetailVC.h"
#import "BTTopicDetailVC.h"
#import "Masonry.h"
static NSString * const cellId = @"CWQ_courseIntroductionCellID";
 CGFloat TopMenuHeight = -64;
@interface BTCouseListVC ()<BTCollectionBottomMenuViewViewDelegate>
@property(nonatomic, assign)BTCourseType type;

@property(nonatomic, strong)CWQ_tableView *tableView;
//上拉加载的页面
@property (nonatomic, assign) NSInteger page;
@property(nonatomic, strong)NSMutableArray *dataSource;
@property(nonatomic, strong)BTCollectionBottomMenuView *bottomMenu;


@end

@implementation BTCouseListVC


- (instancetype)initWithType:(BTCourseType)type {
    if (self = [super init]) {
        _type = type;
        TopMenuHeight = -(64);
    }
    return self;
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    CWQ_tableView *tableView = [[CWQ_tableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64 -49) style:UITableViewStylePlain cellClass:@"CWQ_courseIntroductionCell" vc:self upload:YES];
    [self.view addSubview:tableView];
    _dataSource = [NSMutableArray array];
    _page = 1;
    _tableView = tableView;
    [tableView cwq_requestDataWithDown:YES];

    // Do any additional setup after loading the view.
}


- (void)setDataSource:(NSMutableArray *)dataSource {
    _dataSource = dataSource;
    [self.tableView setupSourceArray:self.dataSource];
}

#pragma -mark- --------------------获取课程列表----------------------

- (void)cwq_tableView:(CWQ_tableView *)tableView requestDataWithDown:(BOOL)down {
    
    if (down) {
        self.page = 1;
    }else {
        self.page++;
    }
    
    tableView.loading = YES;
    NSDictionary *param = @{@"page":@(self.page), @"rows":@10, @"isCollectType":@(self.type)};
    weakSelf_define;
    [[BTNetworkManager sharedMg] POST:BTMyCollectionsUrl parameters:param success:^(id responseObject) {
        
        if ([responseObject[@"success"] boolValue]) {
            NSMutableArray *arr;
            if (weakSelf.type == 1) {
               arr = [BTCourseModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"data"]];
            }else {
                arr = [BTTopicListModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"data"]];
            }
           
            //判断是上拉刷新？  还是下拉加载？
            if (!down) {
                NSMutableArray *muArr = [weakSelf.dataSource mutableCopy];
                
                [muArr addObjectsFromArray:arr];
                weakSelf.dataSource = muArr;
                if ([responseObject[@"data"][@"totalPage"]  isKindOfClass:[NSNull class]] || weakSelf.page == [responseObject[@"data"][@"totalPage"] integerValue]) {
                     tableView.footer.hidden = YES;
                }
                
                [tableView.footer endRefreshing];
            }else {
                if ([responseObject[@"data"][@"totalPage"] isKindOfClass:[NSNull class]]) {
                    
                }else{
                    if (weakSelf.page == [responseObject[@"data"][@"totalPage"] integerValue]) {
                        tableView.footer.hidden = YES;
                    }else {
                        tableView.footer.hidden = NO;
                    }

                }
                weakSelf.dataSource = arr;
                [tableView.header endRefreshing];
            }
            if (weakSelf.dataSource.count<=0) {
                tableView.loading = NO;
            }
        }
        
    } failure:^(NSString *err) {
        
    }];
    
}


- (NSMutableDictionary *)deleteDic {

    if (!_deleteDic) {
        _deleteDic = [@{} mutableCopy];
    }

    return _deleteDic;
}


- (void)setIsEdit:(BOOL)isEdit {

    _isEdit = isEdit;
    [self.tableView setEditing:isEdit animated:YES];
    defineWeakSelf;
//    [UIView animateWithDuration:0.3 animations:^{
    
        if (isEdit) {
            [self.bottomMenu mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.size.mas_equalTo(CGSizeMake(kScreenWidth+2, 44));
                make.left.equalTo(weakSelf.view).with.offset(0);
                make.bottom.equalTo(self.view.mas_bottom).with.offset(TopMenuHeight);
            }];
        }else {
            [self.deleteDic removeAllObjects];
            [self.bottomMenu mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.size.mas_equalTo(CGSizeMake(kScreenWidth+2, 44));
                make.left.equalTo(weakSelf.view).with.offset(0);
                make.bottom.equalTo(self.view.mas_bottom).with.offset(TopMenuHeight + 44);
            }];
        }
//    }];
//    [UIView animateWithDuration:.5 animations:^{
        //更新约束
        [self.view updateConstraintsIfNeeded];
        [self.view layoutIfNeeded];
//    }];

}

- (BTCollectionBottomMenuView *)bottomMenu {
    if (!_bottomMenu) {
        _bottomMenu = [BTCollectionBottomMenuView menuView];
        _bottomMenu.delegate = self;
        defineWeakSelf;
        [self.view addSubview:_bottomMenu];
        [_bottomMenu mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(kScreenWidth+2, 44));
            make.left.equalTo(weakSelf.view).with.offset(0);
            make.bottom.mas_equalTo(weakSelf.view.mas_bottom).with.offset(TopMenuHeight + 44);
            
        }];
    }
    
    return _bottomMenu;
    
}
#pragma mark ----------------tableview代理--------------------------


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CWQ_courseIntroductionCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId forIndexPath:indexPath];
    cell.needShowGaizhang = YES;
    //设置cell 的分割线
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if (self.type == 1) {
       cell.courseModel = self.dataSource[indexPath.row];
    }else {
    
        cell.topicModel = self.dataSource[indexPath.row];
    }

    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 110;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    if (self.isEdit) {
        BTCourseModel *model = [self.dataSource objectAtIndex:indexPath.row];
        [self.deleteDic setObject:model forKey:model.id];
        [self resetDeleteBtnTitle];
        return;
    }
    
    if (self.type == 1) {
        BTTopicListModel *model = self.dataSource[indexPath.row];
        BTCourseDetailVC *courseDetailVC = [BTCourseDetailVC new];
        [self.navigationController setNavigationBarHidden:YES animated:YES];
        courseDetailVC.courseId = [model.id integerValue];
        [self.navigationController pushViewController:courseDetailVC animated:YES];
     
    }else {
        BTTopicListModel *model = self.dataSource[indexPath.row];
        BTTopicDetailVC *vc =[BTTopicDetailVC new];
        [self.navigationController setNavigationBarHidden:YES animated:YES];
        vc.topicId = [model.id integerValue];
        [self.navigationController pushViewController:vc animated:YES];
      
    }
   
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.isEdit) {
        BTCourseModel *model = [self.dataSource objectAtIndex:indexPath.row];
        [self.deleteDic removeObjectForKey:model.id];
        [self resetDeleteBtnTitle];
    }
}

- (void)resetDeleteBtnTitle {
    
    NSString *deleTitle;
    if ([self.deleteDic count] == 0) {
        deleTitle = @"删除";
    }else {
        
        deleTitle = [NSString stringWithFormat:@"删除(%zd)",[self.deleteDic count]];
    }
    [self.bottomMenu.deleteBtn setTitle:deleTitle forState:UIControlStateNormal];
    
}

#pragma mark ----------------bottomMenu代理--------------------------
- (void)cwqMenuView:(BTCollectionBottomMenuView *)menuView clickSelectBtn:(UIButton *)button {
    if ([button.titleLabel.text isEqualToString:@"全选"]) {
        [button setTitle:@"全不选" forState:UIControlStateNormal];
        for (int i = 0; i < self.dataSource.count; i++) {
            
            BTTopicListModel *model = [self.dataSource objectAtIndex:i];
            [self.deleteDic setObject:model forKey:model.id];
            [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0] animated:YES scrollPosition:NO];
            
        }
    }else {
        [button setTitle:@"全选" forState:UIControlStateNormal];
        for (int i = 0; i < self.dataSource.count; i++) {
            BTTopicListModel *model = [self.dataSource objectAtIndex:i];
            [self.deleteDic removeObjectForKey:model.id];
            [self.tableView deselectRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0] animated:YES];
            
        }
    }
    [self resetDeleteBtnTitle];
}

- (void)cwqMenuView:(BTCollectionBottomMenuView *)menuView clickDeleteBtn:(UIButton *)button {
    if (self.deleteDic.count == 0) {
        return;
    }
    [self cancelCollectionIds:[self.deleteDic allKeys]];
    if ([self.deleteDic count] == self.dataSource.count) {
        [self.deleteDic removeAllObjects];
        NSMutableArray *muA = [NSMutableArray arrayWithArray:self.dataSource];
        [muA removeAllObjects];
        self.dataSource = [muA copy];
        [button setTitle:@"删除" forState:UIControlStateNormal];
        return;
    }
    
    NSMutableArray *muA = [self.dataSource mutableCopy];
    [muA removeObjectsInArray:[self.deleteDic allValues]];
    [self.deleteDic removeAllObjects];
    self.dataSource = [muA copy];
    [button setTitle:@"删除" forState:UIControlStateNormal];
    
}

#pragma mark - 取消收藏-------
- (void)cancelCollectionIds:(NSArray *)ids{
    NSMutableDictionary *params =[NSMutableDictionary dictionary];
    cwqHud;
    params[@"ids"] =  [ids componentsJoinedByString:@","];
    params[@"isCollectType"] = @(self.type);
    [[BTNetworkManager sharedMg] POST:BTCancelCollectionUrl parameters:params success:^(id responseObject) {
        if ([responseObject[@"success"] boolValue]) {
            cwqAlertMessage(@"删除成功");
            [self.tableView cwq_requestDataWithDown:YES];
        }
    } failure:^(NSString *err) {
        
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
